#include "precompile.h"

#include "interaction/EventHandler.h"
#include "EventHandlers.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

EventHandlers::EventHandlers()
{
}

EventHandlers::~EventHandlers()
{
}

void EventHandlers::StartEvents(const InteractionInput& input)
{
	m_input = input;
}

IEventHandler* EventHandlers::Push(vclsid clsidEventHandler,EventInfo* info/*=NULL*/)
{
	IObject* eventhandler = NULL;
	CachedEventHandlers::const_iterator itfind = m_cachedEventHandlers.find(clsidEventHandler);
	if (itfind != m_cachedEventHandlers.end())
		eventhandler  =itfind->second.P();
	else
	{
		sys::ObjectPtr objEventHandler;
		objEventHandler.CreateObject(clsidEventHandler);
		m_cachedEventHandlers.insert(std::make_pair(clsidEventHandler,objEventHandler));
		eventhandler = objEventHandler.P();
	}

	EventLoopEnd();
	sys::InterfacePtr<IEventHandler> pIFEventHandler(eventhandler);
	m_activeEventHandlers.push_back(pIFEventHandler);
	EventHandler* eh = (EventHandler*)pIFEventHandler.P();
	eh->StartInteractionInput(m_input.graphics,m_input.interaction);
	if (info)
		eh->SetEventInfo(info);
	EventLoopBegin();

	return pIFEventHandler;
}

uint32 EventHandlers::Count() const
{
	return (uint32)m_activeEventHandlers.size();
}

void EventHandlers::EventLoopBegin()
{
	if (!m_activeEventHandlers.empty())
	{
		m_activeEventHandlers.front()->EventLoopBegin();
	}
}

void EventHandlers::EventLoopEnd()
{
	if (!m_activeEventHandlers.empty())
	{
		m_activeEventHandlers.front()->EventLoopEnd();
		m_activeEventHandlers.erase(m_activeEventHandlers.begin());
	}
}

bool EventHandlers::Event(SystemEventArgs* e)
{
	if (!m_activeEventHandlers.empty())
		return m_activeEventHandlers.front()->Event(e);

	return false;
}

void EventHandlers::Draw()
{
	for (uint32 i  = 0; i < m_activeEventHandlers.size(); ++i)
	{
		IEventHandler* eventHandler = m_activeEventHandlers[i];
		eventHandler->Draw();
	}
}